﻿using DevComponents.AdvTree;
using DevComponents.DotNetBar;
using DevComponents.DotNetBar.Metro;
using DevComponents.DotNetBar.SuperGrid;
using DevComponents.DotNetBar.SuperGrid.Style;
using Kimd.Common;
using Kimd.Communication;
using Kimd.Logic;
using Kimd.Machine;
using Kimd.Motion;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SQLite;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Mime;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using TCHostUse.Toolkit;
using WorkStation.Common;
using WorkStation.Logic;
using WorkStation.UI;
using WorkStation.UI.Controls;

namespace WorkStation
{
    public partial class FormMain : MetroAppForm
    {
        private List<string> _startInfo;
        private MyGridRadialMenuEditControl _speedSet;
        private FormAlarm _alarmForm;
        private List<Form> _functionForms;
        public FormModule ModuleForm;
        public FormDevice DeviceForm;
        public FormHome HomeForm;
        public FormRecipe RecipeForm;
        public FormData DataForm;
        public FormMain(List<string> startInfo)
        {
            InitializeComponent();
            _startInfo = startInfo;
        }
        private void buttonStyleCustom_SelectedColorChanged(object sender, System.EventArgs e)
        {
            m_ColorSelected = true; // Indicate that color was selected for buttonStyleCustom_ExpandChange method
            buttonStyleCustom.CommandParameter = buttonStyleCustom.SelectedColor;
        }
        private void buttonStyleCustom_ColorPreview(object sender, DevComponents.DotNetBar.ColorPreviewEventArgs e)
        {
            if (StyleManager.IsMetro(StyleManager.Style))
            {
                Color baseColor = e.Color;
                StyleManager.MetroColorGeneratorParameters = new DevComponents.DotNetBar.Metro.ColorTables.MetroColorGeneratorParameters(Color.White, baseColor);
            }
            else
                StyleManager.ColorTint = e.Color;
        }
        private bool m_ColorSelected = false;
        private eStyle m_BaseStyle = eStyle.Office2010Silver;
        private void buttonStyleCustom_ExpandChange(object sender, System.EventArgs e)
        {
            if (buttonStyleCustom.Expanded)
            {
                // Remember the starting color scheme to apply if no color is selected during live-preview
                m_ColorSelected = false;
                m_BaseStyle = StyleManager.Style;
            }
            else
            {
                if (!m_ColorSelected)
                {
                    if (StyleManager.IsMetro(StyleManager.Style))
                        StyleManager.MetroColorGeneratorParameters = DevComponents.DotNetBar.Metro.ColorTables.MetroColorGeneratorParameters.Default;
                    else
                        StyleManager.ChangeStyle(m_BaseStyle, Color.Empty);
                }
            }
        }
        private void AppCommandTheme_Executed(object sender, EventArgs e)
        {
            ICommandSource source = sender as ICommandSource;
            if (source.CommandParameter is string)
            {
                eStyle style = (eStyle)Enum.Parse(typeof(eStyle), source.CommandParameter.ToString());
                // Using StyleManager change the style and color tinting
                //if (StyleManager.IsMetro(style))
                //{
                //    if (style == eStyle.Metro)
                //        StyleManager.MetroColorGeneratorParameters = DevComponents.DotNetBar.Metro.ColorTables.MetroColorGeneratorParameters.DarkBlue;

                //    //StyleManager.Style = style; // BOOM
                //    styleManager1.ManagerStyle = style;
                //}
                //else
                //{

                //    // If previous style was Metro we need to update other properties as well
                //    if (StyleManager.IsMetro(StyleManager.Style))
                //    {
                //    }
                    // Adjust tab strip style
                    //tabStrip1.Style = eTabStripStyle.Office2007Document;
                    //StyleManager.ChangeStyle(style, Color.Empty);
                    styleManager1.ManagerStyle = style;
                //}
                SystemConfig.Instance.SystemTheme = source.CommandParameter.ToString();
                SystemConfig.Instance.Save();
            }
            else if (source.CommandParameter is Color)
            {
                //if (StyleManager.IsMetro(StyleManager.Style))
                //    StyleManager.MetroColorGeneratorParameters = new DevComponents.DotNetBar.Metro.ColorTables.MetroColorGeneratorParameters(Color.White, (Color)source.CommandParameter);
                //else
                //    StyleManager.ColorTint = (Color)source.CommandParameter;
                styleManager1.ManagerColorTint = (Color)source.CommandParameter;
                //SystemConfig.Instance.ThemeColor = 
                SystemConfig.Instance.ColorType = styleManager1.ManagerColorTint;
                SystemConfig.Instance.Save();
            }
            buttonChangeStyle.Expanded = false;
        }
        private void rT_TabItem_Click(object sender, EventArgs e)
        {
            if ((sender as RibbonTabItem).Name.Equals("rT_Home"))
            {
                rT_Home.Image = Properties.Resources.HomeBig;
                rT_Module.Image = Properties.Resources.ModuleSmallWhite;
                rT_Recipe.Image = Properties.Resources.RecipeSmallWhite;
                rT_Device.Image = Properties.Resources.DeviceSmallWhite;
                //rT_Data.Image = Properties.Resources.DataSmallWhite;
                switchForm(HomeForm);
            }
            else if ((sender as RibbonTabItem).Name.Equals("rT_Module"))
            {
                rT_Home.Image = Properties.Resources.HomeSmallWhite;
                rT_Module.Image = Properties.Resources.ModuleBig;
                rT_Recipe.Image = Properties.Resources.RecipeSmallWhite;
                rT_Device.Image = Properties.Resources.DeviceSmallWhite;
                //rT_Data.Image = Properties.Resources.DataSmallWhite;
                switchForm(ModuleForm);
            }
            else if ((sender as RibbonTabItem).Name.Equals("rT_Recipe"))
            {
                rT_Home.Image = Properties.Resources.HomeSmallWhite;
                rT_Module.Image = Properties.Resources.ModuleSmallWhite;
                rT_Recipe.Image = Properties.Resources.RecipeBig;
                rT_Device.Image = Properties.Resources.DeviceSmallWhite;
                //rT_Data.Image = Properties.Resources.DataSmallWhite;
                switchForm(RecipeForm);
            }
            else if ((sender as RibbonTabItem).Name.Equals("rT_Device"))
            {
                rT_Home.Image = Properties.Resources.HomeSmallWhite;
                rT_Module.Image = Properties.Resources.ModuleSmallWhite;
                rT_Recipe.Image = Properties.Resources.RecipeSmallWhite;
                rT_Device.Image = Properties.Resources.DeviceBig;
                //rT_Data.Image = Properties.Resources.DataSmallWhite;
                switchForm(DeviceForm);
            }
            else if ((sender as RibbonTabItem).Name.Equals("rT_Data"))
            {
                rT_Home.Image = Properties.Resources.HomeSmallWhite;
                rT_Module.Image = Properties.Resources.ModuleSmallWhite;
                rT_Recipe.Image = Properties.Resources.RecipeSmallWhite;
                rT_Device.Image = Properties.Resources.DeviceSmallWhite;
                //rT_Data.Image = Properties.Resources.DataBig;
                switchForm(DataForm);
            }
        }
        private void switchForm(Form showForm)
        {
            foreach (Form form in p_Form.Controls)
            {
                form.Hide();
            }
            showForm.Show();
        }
        public List<string> GetAllModuleNames()
        {
            List<string> names = new List<string>();
            foreach (var item in MachineResource.Instance.MachineAxis.Values)
            {
                if(!names.Contains(item.Module))
                {
                    names.Add(item.Module);
                }
            }
            foreach (var item in MachineResource.Instance.MachineCylinder.Values)
            {
                if (!names.Contains(item.Module))
                {
                    names.Add(item.Module);
                }
            }
            foreach (var item in MachineResource.Instance.MachineSensor.Values)
            {
                if (!names.Contains(item.Module))
                {
                    names.Add(item.Module);
                }
            }
            return names;
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            #region 加载系统配置
            //SystemConfig.Instance.CardConfig = new List<string>() { "1_DIO8", "2_DI16", "3_DI16", "4_DI16", "5_DI16", "6_DI16", "7_DI16", "8_DI16", "9_DO16", "10_DO16", "11_DO16", "12_DO16", "13_DO16", "14_DO16" };
            //SystemConfig.Instance.Save();
            //GetAllModuleNames().ForEach(name => SystemConfig.Instance.ModuleName2Disable.Add(name, false));
            //SystemConfig.Instance.Save();
            SystemConfig.Instance = SystemConfig.Instance.Load();
            foreach (Kimd.Motion.Axis item in MachineResource.Instance.MachineAxis.Values)
            {
                item.CardConfig = SystemConfig.Instance.CardConfig;
            }
            foreach (Kimd.Motion.Sensor item in MachineResource.Instance.MachineSensor.Values)
            {
                item.CardConfig = SystemConfig.Instance.CardConfig;
            }
            foreach (Kimd.Motion.Cylinder item in MachineResource.Instance.MachineCylinder.Values)
            {
                item.CardConfig = SystemConfig.Instance.CardConfig;
            }
            GlobalVariable.StationResults = XmlSerializerHelper<List<StationTestResult>>.DeserializeFromFile(PathHelper.GetConfigPath("Machine") + "TestData.xml");
            if(GlobalVariable.StationResults == null || GlobalVariable.StationResults.Count == 0)
            {
                GlobalVariable.StationResults = new List<StationTestResult>();
                for (int i = 0; i < 4; i++)
                {
                    StationTestResult st = new StationTestResult();
                    st.NGCounts.Add(1, 0);
                    st.NGCounts.Add(2, 0);
                    st.NGCounts.Add(3, 0);
                    st.NGCounts.Add(4, 0);
                    GlobalVariable.StationResults.Add(st);
                }
                //XmlSerializerHelper<List<StationTestResult>>.SerializeToFile(GlobalVariable.StationResults, PathHelper.GetConfigPath("Machine") + "TestData.xml");
            }
            GlobalVariable.CurrentMachineData = XmlSerializerHelper<MachineData>.DeserializeFromFile(PathHelper.GetConfigPath("Machine") + "MachineData.xml");
            if(GlobalVariable.CurrentMachineData == null)
            {
                GlobalVariable.CurrentMachineData = new MachineData();
                //XmlSerializerHelper<MachineData>.SerializeToFile(GlobalVariable.CurrentMachineData, PathHelper.GetConfigPath("Machine") + "MachineData.xml");
            }
            GlobalVariable.AlarmDict = XmlSerializerHelper<SerializableDictionary<string, int>>.DeserializeFromFile(PathHelper.GetConfigPath("Machine") + "Alarm.xml");
            if (GlobalVariable.AlarmDict == null)
            {
                GlobalVariable.AlarmDict = new SerializableDictionary<string, int>();
                //XmlSerializerHelper<SerializableDictionary<string, int>>.SerializeToFile(GlobalVariable.AlarmDict, PathHelper.GetConfigPath("Machine") + "Alarm.xml");
            }
            #endregion

            #region 加载数据库
            bool isExist = false;
            DataTable dt = GetTableStatus();
            if(dt != null)
            {
                foreach (DataRow dataRow in dt.Rows)
                {
                    if (dataRow["tbl_name"].Equals("WarnList"))
                    {
                        isExist = true;
                        break;
                    }
                }
            }
            if (!isExist)
            {
                CreateTable("WarnList", new List<SQLiteColumn>() { new SQLiteColumn("StartTime", ColType.DateTime, false, false, true, ""),
                                                                   new SQLiteColumn("Level", ColType.Text, false, false, true, "0"),
                                                                   new SQLiteColumn("Source", ColType.Text, false, false, true, "0"),
                                                                   new SQLiteColumn("Content", ColType.Text, false, false, true, ""),
                                                                   new SQLiteColumn("Module", ColType.Text, false, false, true, ""),
                                                                   new SQLiteColumn("ID", ColType.Integer, true, true, true, "0")});
            }

            #endregion

            #region UI初始化
            _functionForms = new List<Form>();

            ModuleForm = new FormModule(this);
            ModuleForm.TopLevel = false;
            ModuleForm.Dock = DockStyle.Fill;
            this.p_Form.Controls.Add(ModuleForm);
            _functionForms.Add(ModuleForm);

            DeviceForm = new FormDevice(this);
            DeviceForm.TopLevel = false;
            DeviceForm.Dock = DockStyle.Fill;
            this.p_Form.Controls.Add(DeviceForm);
            _functionForms.Add(DeviceForm);

            HomeForm = new FormHome(this);
            HomeForm.TopLevel = false;
            HomeForm.Dock = DockStyle.Fill;
            this.p_Form.Controls.Add(HomeForm);
            HomeForm.Show();
            _functionForms.Add(HomeForm);

            RecipeForm = new FormRecipe(this);
            RecipeForm.TopLevel = false;
            RecipeForm.Dock = DockStyle.Fill;
            this.p_Form.Controls.Add(RecipeForm);
            _functionForms.Add(RecipeForm);
            HomeForm.UpdateMesOPID += RecipeForm.UpdateMesParam;

            DataForm = new FormData(this);
            DataForm.TopLevel = false;
            DataForm.Dock = DockStyle.Fill;
            this.p_Form.Controls.Add(DataForm);
            _functionForms.Add(DataForm);

            if (!string.IsNullOrEmpty(SystemConfig.Instance.SystemTheme))
                this.styleManager1.ManagerStyle = (eStyle)Enum.Parse(typeof(eStyle), SystemConfig.Instance.SystemTheme.ToString());
            if (SystemConfig.Instance.ColorType != null)
            {
                if (StyleManager.IsMetro(StyleManager.Style))
                {
                    Color baseColor = SystemConfig.Instance.ColorType;
                    StyleManager.MetroColorGeneratorParameters = new DevComponents.DotNetBar.Metro.ColorTables.MetroColorGeneratorParameters(Color.White, baseColor);
                }
                else
                    StyleManager.ColorTint = SystemConfig.Instance.ColorType;
            }

            Task uiTask = new Task(new Action(updateUI));
            uiTask.Start();
            Task uiLogTask = new Task(new Action(updateUILog));
            uiLogTask.Start();

            foreach (var item in _functionForms)
            {
                GlobalVariable.UserRole.OnUserRoleChanged += (item as IUserChange).UserChanged;
            }
            l_User2.Text = $"{GlobalVariable.UserRole.ToString()}";
            GlobalVariable.UserRole.OnUserRoleChanged += UserChanged;

            _alarmForm = new FormAlarm(this);
            #endregion

            #region 加载逻辑

            FeedHeaderLogic feedHeadLogic = new FeedHeaderLogic("取料逻辑", FlowManager.Instance);
            feedHeadLogic.Status.IsEnabled = true;
            FlowManager.Instance.AddFlow(feedHeadLogic);

            FeedTrayLogic feedTrayLogic = new FeedTrayLogic("上Tray模组", FlowManager.Instance);
            feedTrayLogic.Status.IsEnabled = true;
            FlowManager.Instance.AddFlow(feedTrayLogic);

            TesterStatusLogic testerStatusLogic = new TesterStatusLogic("测试机状态1", FlowManager.Instance, 0, "192.168.1.88");
            testerStatusLogic.Status.IsEnabled = true;
            testerStatusLogic.Status.IsBackground = true;
            FlowManager.Instance.AddFlow(testerStatusLogic);

            TesterStatusLogic testerStatusLogic2 = new TesterStatusLogic("测试机状态2", FlowManager.Instance, 1, "192.168.1.89");
            testerStatusLogic2.Status.IsEnabled = false;
            testerStatusLogic2.Status.IsBackground = true;
            FlowManager.Instance.AddFlow(testerStatusLogic2);

            FeedTesterLogic feedTesterLogic = new FeedTesterLogic("治具上料模组", FlowManager.Instance);
            feedTesterLogic.Status.IsEnabled = true;
            FlowManager.Instance.AddFlow(feedTesterLogic);

            UnloadTesterLogic unloadTesterLogic = new UnloadTesterLogic("下料逻辑", FlowManager.Instance);
            unloadTesterLogic.Status.IsEnabled = true;
            FlowManager.Instance.AddFlow(unloadTesterLogic);

            UnloadTrayLogic unloadTrayLogic = new UnloadTrayLogic("下Tray模组", FlowManager.Instance);
            unloadTrayLogic.Status.IsEnabled = true;
            FlowManager.Instance.AddFlow(unloadTrayLogic);

            SimTesterLogic simTesterLogic1 = new SimTesterLogic("测试治具1", FlowManager.Instance, 0);
            simTesterLogic1.Status.IsEnabled = true;
            FlowManager.Instance.AddFlow(simTesterLogic1);

            SimTesterLogic simTesterLogic2 = new SimTesterLogic("测试治具2", FlowManager.Instance, 1);
            simTesterLogic2.Status.IsEnabled = true;
            FlowManager.Instance.AddFlow(simTesterLogic2);


            foreach (var item in FlowManager.Instance.Flows.Values)
            {
                item.Open();
            }

            l_Status.Text = "READY";
            cP_Status.Visible = false;
            #endregion

            HomeForm.UpdateFlowStatus();


            if (MachineResource.Instance.MachineCylinder.ContainsKey("绿灯"))
            {
                GlobalVariable.ColorLight = new ThreeColorLight(MachineResource.Instance.MachineCylinder["绿灯"],
                                                                MachineResource.Instance.MachineCylinder["红灯"],
                                                                MachineResource.Instance.MachineCylinder["黄灯"],
                                                                MachineResource.Instance.MachineCylinder["蜂鸣器"]);
            }

            labelItem29.BorderType = GlobalVariable.IsSafeDoorCheck ? eBorderType.Sunken : eBorderType.Raised;
            labelItem29.Text = GlobalVariable.IsSafeDoorCheck ? "启用" : "禁用";
            labelItem29.BackColor = GlobalVariable.IsSafeDoorCheck ? Color.Transparent : Color.Red;
            labelItem29.ForeColor = GlobalVariable.IsSafeDoorCheck ? Color.LimeGreen : Color.White;

            labelItem24.BorderType = SystemConfig.Instance.UsingStatus.IsScannerInUse ? eBorderType.Sunken : eBorderType.Raised;
            labelItem24.Text = SystemConfig.Instance.UsingStatus.IsScannerInUse ? "启用" : "禁用";
            labelItem24.BackColor = SystemConfig.Instance.UsingStatus.IsScannerInUse ? Color.Transparent : Color.Red;
            labelItem24.ForeColor = SystemConfig.Instance.UsingStatus.IsScannerInUse ? Color.LimeGreen : Color.White;

            //默认不启用压测
            SystemConfig.Instance.UsingStatus.IsCosmetic = false;
            SystemConfig.Instance.Save();

            l_Version.Text = Assembly.GetExecutingAssembly().GetName().Version.ToString();
            l_Recipe.Text = "当前配方:" + Properties.Settings.Default.ConfigName;
            if (MachineResource.Instance.MachineTcpClient.ContainsKey("一键熄屏1"))
            {
                TCPClient client = MachineResource.Instance.MachineTcpClient["一键熄屏1"];
                client.DatagramReceived -= Client_DatagramReceived1;
                client.DatagramReceived += Client_DatagramReceived1;
            }
            if (MachineResource.Instance.MachineTcpClient.ContainsKey("一键熄屏2"))
            {
                TCPClient client = MachineResource.Instance.MachineTcpClient["一键熄屏2"];
                client.DatagramReceived -= Client_DatagramReceived2;
                client.DatagramReceived += Client_DatagramReceived2;
            }
            //MachineResource.Instance.MachineCylinder["精定位1下层移载气缸"].PreCheckOn = check5;
            //MachineResource.Instance.MachineCylinder["精定位2下层移载气缸"].PreCheckOn = check6;
            //MachineResource.Instance.MachineCylinder["精定位1上层移载气缸"].PreCheckOn = check5;
            //MachineResource.Instance.MachineCylinder["精定位2上层移载气缸"].PreCheckOn = check6;
        }
        private (bool, string) check5()
        {
            if (GlobalVariable.RobotZInNotSafeArea[0])
            {
                return (false, "机器人1Z轴不在安全位，无法移动气缸");
            }
            return (true, "");
        }
        private (bool, string) check6()
        {
            if (GlobalVariable.RobotZInNotSafeArea[1])
            {
                return (false, "机器人2Z轴不在安全位，无法移动气缸");
            }
            return (true, "");
        }
        public void UserChanged()
        {
            if (GlobalVariable.UserRole.UserLevel == 2)
            {
                lbl_handlerMes.Enabled = true;
                this.labelItem29.Enabled = true;
                this.labelItem24.Enabled = true;
            }
            else if (GlobalVariable.UserRole.UserLevel == 0)
            {
                lbl_handlerMes.Enabled = false;
                this.labelItem29.Enabled = false;
                this.labelItem24.Enabled = false;
            }
            else if (GlobalVariable.UserRole.UserLevel == 1)
            {
                lbl_handlerMes.Enabled = true;
                this.labelItem29.Enabled = true;
                this.labelItem24.Enabled = true;
            }
        }
        private void FormMain_CommRunDisplay(Kimd.Communication.TCPClient arg1, string arg2)
        {
            MachineMessageScheduler.Instance.Add(new MachineMessage(MessageType.Log, $"{arg2}", "Main", 0, "系统"));
        }
        bool isClosing = false;
        private void updateUI()
        {
            while (true)
            {
                MachineMessage message = null;
                if (MachineMessageScheduler.Instance.GetMessage(out message))
                {
                    #region 日志动作
                    if (message.MessageType != MessageType.Count &&
                        message.MessageType != MessageType.CT &&
                        message.MessageType != MessageType.Pie)
                    {
                        HomeForm.AddOneLog(message);
                        MessageLevel ml = MessageLevel.Log;
                        if (message.MessageType == MessageType.Warn)
                            ml = MessageLevel.Warn;
                        else if (message.MessageType == MessageType.Error)
                            ml = MessageLevel.Error;
                        else if (message.MessageType == MessageType.InfoAndPause)
                            ml = MessageLevel.InfoAndPause;
                        if (message.MessageType == MessageType.Warn || message.MessageType == MessageType.Error || message.MessageType == MessageType.Info || message.MessageType == MessageType.InfoAndPause)
                        {
                            HomeForm.AddOneWarn(message);
                        }
                        if (message.MessageType == MessageType.Warn || message.MessageType == MessageType.Error)
                        {
                            updateAlarmList(message);
                        }
                        LogHelper.Instance.Log(message.MessageSource, message.MessageBody, ml, message.MessageException);
                    }

                    if (message.MessageType == MessageType.CT)
                    {
                        MessageLevel ml = MessageLevel.Log;
                        LogHelper.Instance.Log(message.MessageSource, message.MessageBody, ml, message.MessageException);
                    }
                    #endregion
                    #region 报警动作
                    //这两种报警需要等待确认后方可继续
                    if (message.MessageType == MessageType.Warn || message.MessageType == MessageType.Error || message.MessageType == MessageType.Info || message.MessageType == MessageType.InfoAndPause)
                    {
                        if (message.MessageType != MessageType.InfoAndPause)
                        {
                            GlobalVariable.RobotControlStatus[(int)RobotoutEnumRobot1.机器人停止] = false;
                            GlobalVariable.RobotControlStatus[(int)RobotoutEnumRobot1.机器人程序启动] = false;
                            GlobalVariable.RobotControlStatus2[(int)RobotoutEnumRobot2.机器人停止] = false;
                            GlobalVariable.RobotControlStatus2[(int)RobotoutEnumRobot2.机器人程序启动] = false;
                        }
                        GlobalVariable.IsSystemErr = true;
                        if (this.IsHandleCreated)
                        {
                            this.BeginInvoke(new Action(() =>
                            {
                                HomeForm.PauseClickUI();
                            }));
                        }
                    }
                    switch (message.MessageType)
                    {
                        case MessageType.Warn:
                        case MessageType.Error:
                        case MessageType.Info:
                        case MessageType.InfoAndPause:
                            if(!string.IsNullOrEmpty(message.Module))
                            {
                                HomeForm.ModuleWarn(message.Module);
                            }
                            break;
                    }
                    #endregion
                    #region DownTime计数
                    if (message.MessageType == MessageType.Warn
                        || message.MessageType == MessageType.Error)
                    {
                        if (!GlobalVariable.IsDownTimeFlag)
                        {
                            GlobalVariable.IsDownTimeFlag = true;
                            GlobalVariable.DownTimeMonitor.Restart();
                        }
                    }
                    #endregion
                    #region 报警确认
                    //这两种报警需要等待确认后方可继续
                    if (message.MessageType == MessageType.Warn || message.MessageType == MessageType.Error || message.MessageType == MessageType.Info || message.MessageType == MessageType.InfoAndPause)
                    {
                        //等待报警复位
                        while(GlobalVariable.IsSystemErr && !isClosing)
                        {
                            Thread.Sleep(20);
                        }
                        if (!string.IsNullOrEmpty(message.Module))
                        {
                            if (!HomeForm.IsDisposed)
                                HomeForm.ModuleReset(message.Module);
                        }
                    }
                    #endregion
                }
                Thread.Sleep(20);
            }
        }

        private void updateUILog()
        {
            while (true)
            {
                MachineMessage message = null;
                if (MachineMessageScheduler.Instance.GetMessageLog(out message))
                {
                    #region 日志动作
                    if (message.MessageType != MessageType.Count &&
                        message.MessageType != MessageType.CT &&
                        message.MessageType != MessageType.Pie)
                    {
                        HomeForm.AddOneLog(message);
                        MessageLevel ml = MessageLevel.Log;
                        if (message.MessageType == MessageType.Warn)
                            ml = MessageLevel.Warn;
                        else if (message.MessageType == MessageType.Error)
                            ml = MessageLevel.Error;
                        else if (message.MessageType == MessageType.InfoAndPause)
                            ml = MessageLevel.InfoAndPause;
                        if (message.MessageType == MessageType.Warn || message.MessageType == MessageType.Error || message.MessageType == MessageType.Info || message.MessageType == MessageType.InfoAndPause)
                        {
                            HomeForm.AddOneWarn(message);
                        }
                        if (message.MessageType == MessageType.Warn || message.MessageType == MessageType.Error)
                        {
                            updateAlarmList(message);
                        }
                        LogHelper.Instance.Log(message.MessageSource, message.MessageBody, ml, message.MessageException);
                    }
                    #endregion
                    #region 更新CT
                    if (message.MessageType == MessageType.CT)
                    {
                        this.BeginInvoke(new Action(() =>
                        {
                            HomeForm.UpdateCT(message.Module, message.MessageBody);
                        }));
                    }
                    #endregion
                    #region 更新数量
                    if (message.MessageType == MessageType.Count)
                    {
                        this.BeginInvoke(new Action(() =>
                        {
                            HomeForm.UpdateCount(message.Module, message.MessageBody);
                        }));
                    }
                    #endregion
                    #region 更新饼图
                    if (message.MessageType == MessageType.Pie)
                    {
                        this.BeginInvoke(new Action(() =>
                        {
                            //HomeForm.UpdatePie(message.Module, message.MessageBody);
                        }));
                    }
                    #endregion
                }
                Thread.Sleep(20);
            }
        }
        private void updateAlarmList(MachineMessage message)
        {
            Dictionary<string, object> data = new Dictionary<string, object>();
            data.Add("StartTime", message.StartTime);
            data.Add("Level", EnumHelper.GetEnumDescriptionFromValue(message.MessageType));
            data.Add("Source", message.MessageSource);
            data.Add("Content", message.MessageBody);
            if (message.Module == null)
                message.Module = "undefined";
            data.Add("Module", message.Module);
            InsertOneRecord("WarnList", data);

            if (GlobalVariable.AlarmDict.ContainsKey(message.MessageBody))
                GlobalVariable.AlarmDict[message.MessageBody] += 1;
            else
                GlobalVariable.AlarmDict.Add(message.MessageBody, 1);
            XmlSerializerHelper<SerializableDictionary<string, int>>.SerializeToFile(GlobalVariable.AlarmDict, PathHelper.GetConfigPath("Machine") + "Alarm.xml");

            if(!HomeForm.IsDisposed)
                HomeForm.UpdateWarnStatics();
        }
        public void Switch2Module()
        {
            rT_TabItem_Click(rT_Module, null);
            this.ribbonControl1.SelectedRibbonTabItem = rT_Module;
        }
        bool isEmergencyStop = false;
        int count = 0;
        bool isConveyorWarn = false;
        private void t_System_Tick(object sender, EventArgs e)
        {
            //HomeForm.UpdateUPH("2024");
            this.labelItem15.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            //MachineMessage message;
            //if(MachineMessageScheduler.Instance.GetMessage(out message))
            //{
            //    SystemInfo.ShowToastInfo(this, message.MessageBody, true);
            //}
            if (MachineResource.Instance.MachineCard != null && MachineResource.Instance.MachineCard.ContainsKey("card1"))
            {
                l_EtherCAT.Text = MachineResource.Instance.MachineCard["card1"].IsErr ? $"异常:{MachineResource.Instance.MachineCard["card1"].LastErrorMessage}" : "正常";
                l_EtherCAT.ForeColor = MachineResource.Instance.MachineCard["card1"].IsErr ? Color.Red : Color.LimeGreen;
            }


            if (MachineResource.Instance.MachineSensor.ContainsKey("设备急停") &&
                !MachineResource.Instance.MachineSensor["设备急停"].WaitOn() && !isEmergencyStop)
            {
                GlobalVariable.ColorLight?.Warn();
                isEmergencyStop = true;
                foreach (var item in MachineResource.Instance.MachineAxis.Values)
                {
                    item.Stop(true);
                }
                MachineMessageScheduler.Instance.Add(new MachineMessage(MessageType.Warn, $"急停按下!!!请停止所有流程后进行原点复归", "Main", 11, "系统"));
                //出错，停下所有线程
                FlowManager.Instance.Pause();
                GlobalVariable.IsSystemAlreadyHome = false; 

            }
            else if(MachineResource.Instance.MachineSensor.ContainsKey("设备急停") && MachineResource.Instance.MachineSensor["设备急停"].WaitOn())
            {
                isEmergencyStop = false;
            }
            if (MachineResource.Instance.MachineSensor.ContainsKey("前门禁1"))
            {
                if ((isDoorOpen()) && !GlobalVariable.isSafeDoorOpen && GlobalVariable.IsSafeDoorCheck)
                {
                    GlobalVariable.ColorLight.Warn();
                    GlobalVariable.isSafeDoorOpen = true;
                    MachineMessageScheduler.Instance.Add(new MachineMessage(MessageType.Warn, $"安全门打开", "Main", 0, "系统"));

                    HomeForm.btn_Pause.PerformClick();
                }
                else if (!isDoorOpen() && GlobalVariable.IsSafeDoorCheck)
                {
                    GlobalVariable.isSafeDoorOpen = false;
                }
            }
            if (MachineResource.Instance.MachineSensor.ContainsKey("前门光栅1"))
            {
                //if ((isSafeLightOpen(true))&& !GlobalVariable.isSafeLightOpenFront && !SystemConfig.Instance.UsingStatus.IsFrontDisable)
                //{
                   
                //    GlobalVariable.ColorLight.Warn();
                //    GlobalVariable.isSafeLightOpenFront = true;
                //    MachineMessageScheduler.Instance.Add(new MachineMessage(MessageType.Warn, $"前线光栅触碰", "Main", 0, "系统"));

                //    HomeForm.btn_Pause.PerformClick();
                //}
                //else if ((!isSafeLightOpen(true)) && !SystemConfig.Instance.UsingStatus.IsFrontDisable)
                //{
                //    GlobalVariable.isSafeLightOpenFront = false;
                //}

                //if ((isSafeLightOpen(false)) && !GlobalVariable.isSafeLightOpenBack && !SystemConfig.Instance.UsingStatus.IsBackDisable)
                //{

                //    GlobalVariable.ColorLight.Warn();
                //    GlobalVariable.isSafeLightOpenBack = true;
                //    MachineMessageScheduler.Instance.Add(new MachineMessage(MessageType.Warn, $"后线光栅触碰", "Main", 0, "系统"));

                //    HomeForm.btn_Pause.PerformClick();
                //}
                //else if ((!isSafeLightOpen(false)) && !SystemConfig.Instance.UsingStatus.IsBackDisable)
                //{
                //    GlobalVariable.isSafeLightOpenBack = false;
                //}
            }

            if (GlobalVariable.PCReadPLCData[(int)EnumHelper.GetEnumValueFromDescription<PLCInFlag>("轨道PLC报警")] && !isConveyorWarn)
            {
                isConveyorWarn = true;
                MachineMessageScheduler.Instance.Add(new MachineMessage(MessageType.Info, "轨道PLC报警", "系统", 0, "Robot1模组"));
            }
            else if (!GlobalVariable.PCReadPLCData[(int)EnumHelper.GetEnumValueFromDescription<PLCInFlag>("轨道PLC报警")])
            {
                isConveyorWarn = false;
            }

            count++;
            if(count >= 20)
            {
                count = 0;
                //switch(GlobalVariable.MachineWorkMode)
                //{
                //    case WorkMode.Auto:
                //        l_Mode.Text = "模式:生产";
                //        break;
                //    case WorkMode.Calibrate:
                //        l_Mode.Text = "模式:标定";
                //        break;
                //    case WorkMode.GRR:
                //        l_Mode.Text = "模式:GRR";
                //        break;
                //}
                //if(GlobalVariable.IsSpotChecking)
                //    l_Mode.Text = "模式:点检";
                //if (GlobalVariable.IsDryRun)
                //{
                //    l_Mode.Text += ",空跑";
                //}
                //l_Mode.ForeColor = l_Mode.ForeColor == Color.White ? Color.IndianRed : Color.White;
            }

            labelItem24.BorderType = SystemConfig.Instance.UsingStatus.IsScannerInUse ? eBorderType.Sunken : eBorderType.Raised;
            labelItem24.Text = SystemConfig.Instance.UsingStatus.IsScannerInUse ? "启用" : "禁用";
            labelItem24.BackColor = SystemConfig.Instance.UsingStatus.IsScannerInUse ? Color.Transparent : Color.Red;
            labelItem24.ForeColor = SystemConfig.Instance.UsingStatus.IsScannerInUse ? Color.LimeGreen : Color.White;
        }
        public void Stopping()
        {
            l_Status.Text = "STOPPING...";
            cP_Status.IsRunning = true;
            cP_Status.Visible = true;
            l_Status.ForeColor = Color.White;
        }
        public void Stopped()
        {
            l_Status.Text = "STOPPED!";
            cP_Status.IsRunning = false;
            cP_Status.Visible = false;
            l_Status.ForeColor = Color.White;
        }
        public void Homing()
        {
            l_Status.Text = "HOMING...";
            cP_Status.IsRunning = true;
            cP_Status.Visible = true;
            l_Status.ForeColor = Color.White;
        }
        public void HomeFinished()
        {
            l_Status.Text = "HOME FINISHED!";
            cP_Status.IsRunning = false;
            cP_Status.Visible = false;
            l_Status.ForeColor = Color.White;
        }
        private void button1_Click(object sender, EventArgs e)
        {
        }
        private bool isSafeLightOpen(bool isFront)
        {
            if (isFront)
            {
                return !MachineResource.Instance.MachineSensor["前门光栅1"].WaitOn() ||
                                  !MachineResource.Instance.MachineSensor["前门光栅2"].WaitOn();
            }
            else
            {
                return !MachineResource.Instance.MachineSensor["后门光栅1"].WaitOn() ||
                                    !MachineResource.Instance.MachineSensor["后门光栅2"].WaitOn();
            }
        }
        private bool isDoorOpen()
        {
            return !MachineResource.Instance.MachineSensor["前门禁1"].WaitOn() ||
                   !MachineResource.Instance.MachineSensor["前门禁2"].WaitOn() ||
                   !MachineResource.Instance.MachineSensor["前门禁3"].WaitOn() ||
                   !MachineResource.Instance.MachineSensor["前门禁4"].WaitOn() ||
                   !MachineResource.Instance.MachineSensor["后门禁1"].WaitOn() ||
                   !MachineResource.Instance.MachineSensor["后门禁2"].WaitOn() ||
                   !MachineResource.Instance.MachineSensor["后门禁3"].WaitOn() ||
                   !MachineResource.Instance.MachineSensor["后门禁4"].WaitOn();
        }
        private void btnPause_Click(object sender, EventArgs e)
        {

        }

        private void btnStop_Click(object sender, EventArgs e)
        {

        }

        private void btnStartHome_Click(object sender, EventArgs e)
        {

        }
        public void ChartAlarmDistributionMethod(Chart _Chart, List<AlarmDistribution> list)
        {
            //清空chart图表
            _Chart.Series["Series1"].Points.Clear();

            // 设置圆柱宽度
            _Chart.Series["Series1"]["PointWidth"] = "0.3";

            List<Color> colorList = new List<Color>();
            colorList.Add(Color.FromArgb(255, 192, 192));
            colorList.Add(Color.FromArgb(255, 224, 192));
            colorList.Add(Color.FromArgb(255, 255, 192));
            colorList.Add(Color.FromArgb(192, 255, 192));
            colorList.Add(Color.FromArgb(192, 255, 255));
            colorList.Add(Color.FromArgb(192, 192, 255));
            colorList.Add(Color.FromArgb(255, 192, 255));
            colorList.Add(Color.FromArgb(255, 192, 192));
            colorList.Add(Color.FromArgb(255, 224, 192));
            colorList.Add(Color.FromArgb(255, 255, 192));
            colorList.Add(Color.FromArgb(192, 255, 192));
            colorList.Add(Color.FromArgb(192, 255, 255));
            colorList.Add(Color.FromArgb(192, 192, 255));
            colorList.Add(Color.FromArgb(255, 192, 255));
            //
            for (int i = 0; i < list.Count; i++)
            {
                _Chart.Series["Series1"].Points.AddXY(list[i].AlarmName, list[i].AlarmNum);
                _Chart.Series["Series1"].Points[i].Label = list[i].AlarmNum + "次";
                _Chart.Series["Series1"].Points[i].Color = colorList[i];
            }
        }
        public Dictionary<K, V> DescSortByValue<K, V>(Dictionary<K, V> dictionary)
        {
            var result = from obj in dictionary orderby obj.Value descending select obj;
            Dictionary<K, V> descSortByValue = new Dictionary<K, V>();
            foreach (var item in result)
            {
                descSortByValue.Add(item.Key, item.Value);
            }
            return descSortByValue;
        } 
        private void panelEx9_Resize(object sender, EventArgs e)
        {
        }
        private void Theme_Click(object sender, EventArgs e)
        {
            //eStyle style = (eStyle)Enum.Parse(typeof(eStyle), (sender as ButtonItem).CommandParameter.ToString());
            //styleManager1.ManagerStyle = style;
            SystemConfig.Instance.ThemeName = (sender as ButtonItem).Text;
            SystemConfig.Instance.Save();
        }
        private void buttonChangeStyle_PopupOpen(object sender, PopupOpenEventArgs e)
        {
            if (!string.IsNullOrEmpty(SystemConfig.Instance.ThemeName))
            {
                foreach (var item in buttonChangeStyle.SubItems)
                {
                    if((item as ButtonItem).Text.Equals(SystemConfig.Instance.ThemeName))
                        (item as ButtonItem).Checked = true;
                    else
                        (item as ButtonItem).Checked = false;
                }
            }
        }
        private async void FormMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("确认关闭程序吗?", "关闭", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
            {
                HomeForm?.ResetSignalToPLC();
                isClosing = true;
                GlobalVariable.IsSystemErr = false;

                FlowManager.Instance.Stop();

                await Task.Run(() =>
                {
                    while (!FlowManager.Instance.AllFlowStopped)
                    {
                        Thread.Sleep(2);
                    }
                    return true;
                });

                FlowManager.Instance.Close();
                GlobalVariable.ColorLight?.Close();
                MachineResource.Instance.StopMonitor();
                foreach (var item in MachineResource.Instance.MachineAxis)
                {
                    item.Value.Stop(false);
                }
            }
            else
                e.Cancel = true;
        }

        private void btn_Info_Click(object sender, EventArgs e)
        {
            FormInfo infoForm = new FormInfo();
            infoForm.StartPosition = FormStartPosition.CenterScreen;
            infoForm.ShowDialog();
        }

        private void btn_User_Click(object sender, EventArgs e)
        {
            FormLogin loginForm = new FormLogin();
            loginForm.StartPosition = FormStartPosition.CenterScreen;
            if(loginForm.ShowDialog() == DialogResult.OK)
            {
                l_User2.Text = $"{GlobalVariable.UserRole.ToString()}";
                switch(GlobalVariable.UserRole.ToString())
                {
                    case "作业员":
                        l_User2.ForeColor = Color.Purple;
                        break;
                    case "工程师":
                        l_User2.ForeColor = Color.Yellow;
                        break;
                    case "管理员":
                        l_User2.ForeColor = Color.OrangeRed;
                        break;
                }
            }
        }

        private void buttonItem31_Click(object sender, EventArgs e)
        {
            //GlobalVariable.RobotControlStatus[1] = !GlobalVariable.RobotControlStatus[1];
        }

        private void buttonItem32_Click(object sender, EventArgs e)
        {
            //GlobalVariable.RobotControlStatus[0] = !GlobalVariable.RobotControlStatus[0];
        }

        private void buttonItem29_Click(object sender, EventArgs e)
        {
            if (_alarmForm == null || _alarmForm.IsDisposed)
            {
                _alarmForm = new FormAlarm(this);
                _alarmForm.StartPosition = FormStartPosition.CenterScreen;
                _alarmForm.Show();
            }
            else
            {
                if (_alarmForm.WindowState == FormWindowState.Minimized)
                    _alarmForm.WindowState = FormWindowState.Normal;
                if (!_alarmForm.Visible)
                    _alarmForm.Show();
                _alarmForm.BringToFront();
            }
        }
        #region 数据库操作
        public DataTable GetTableStatus()
        {
            using (SQLiteConnection conn = new SQLiteConnection(string.Format("data source={0}", PathHelper.GetConfigPath("Database") + "data")))
            {
                using (SQLiteCommand cmd = new SQLiteCommand())
                {
                    conn.Open();
                    cmd.Connection = conn;

                    SQLiteHelper sh = new SQLiteHelper(cmd);

                    DataTable dt = sh.GetTableStatus();

                    conn.Close();

                    return dt;
                }
            }
        }
        public void CreateTable(string tableName, List<SQLiteColumn> columns)
        {
            SQLiteTable tb = new SQLiteTable(tableName);
            foreach (var col in columns)
            {
                tb.Columns.Add(col);
            }
            using (SQLiteConnection conn = new SQLiteConnection(string.Format("data source={0}", PathHelper.GetConfigPath("Database") + "data")))
            {
                using (SQLiteCommand cmd = new SQLiteCommand())
                {
                    conn.Open();
                    cmd.Connection = conn;

                    SQLiteHelper sh = new SQLiteHelper(cmd);

                    sh.DropTable(tableName);
                    sh.CreateTable(tb);

                    conn.Close();
                }
            }
        }
        public void InsertOneRecord(string tableName, Dictionary<string, object> data)
        {
            using (SQLiteConnection conn = new SQLiteConnection(string.Format("data source={0}", PathHelper.GetConfigPath("Database") + "data")))
            {
                using (SQLiteCommand cmd = new SQLiteCommand())
                {
                    cmd.Connection = conn;
                    conn.Open();

                    SQLiteHelper sh = new SQLiteHelper(cmd);

                    sh.Insert(tableName, data);

                    conn.Close();
                }
            }
        }
        public DataTable Select(string sql, out string errInfo)
        {
            errInfo = "";
            using (SQLiteConnection conn = new SQLiteConnection(string.Format("data source={0}", PathHelper.GetConfigPath("Database") + "data")))
            {
                using (SQLiteCommand cmd = new SQLiteCommand())
                {
                    conn.Open();
                    cmd.Connection = conn;

                    SQLiteHelper sh = new SQLiteHelper(cmd);
                    DataTable dt = null;
                    try
                    {
                        dt = sh.Select(sql);
                    }
                    catch (Exception ex)
                    {
                        errInfo = ex.Message;
                    }

                    conn.Close();
                    return dt;
                }
            }
        }
        #endregion

        private void bI_Log_Click(object sender, EventArgs e)
        {
            string v_OpenFolderPath = @"D:\Log";
            System.Diagnostics.Process.Start("explorer.exe", v_OpenFolderPath);
        }

        private void labelItem24_Click(object sender, EventArgs e)
        {
            //SystemConfig.Instance.UsingStatus.IsScannerInUse = !SystemConfig.Instance.UsingStatus.IsScannerInUse;
            //labelItem24.BorderType = SystemConfig.Instance.UsingStatus.IsScannerInUse ? eBorderType.Sunken : eBorderType.Raised;
            //labelItem24.Text = SystemConfig.Instance.UsingStatus.IsScannerInUse ? "启用" : "禁用";
            //labelItem24.BackColor = SystemConfig.Instance.UsingStatus.IsScannerInUse ? Color.Transparent : Color.Red;
            //labelItem24.ForeColor = SystemConfig.Instance.UsingStatus.IsScannerInUse ? Color.LimeGreen : Color.White;
            //SystemConfig.Instance.Save();
        }

        private void labelItem29_Click(object sender, EventArgs e)
        {
            GlobalVariable.IsSafeDoorCheck = !GlobalVariable.IsSafeDoorCheck;
            labelItem29.BorderType = GlobalVariable.IsSafeDoorCheck ? eBorderType.Sunken : eBorderType.Raised;
            labelItem29.Text = GlobalVariable.IsSafeDoorCheck ? "启用" : "禁用";
            labelItem29.BackColor = GlobalVariable.IsSafeDoorCheck ? Color.Transparent : Color.Red;
            labelItem29.ForeColor = GlobalVariable.IsSafeDoorCheck ? Color.LimeGreen : Color.White;
        }

        private void labelItem32_Click(object sender, EventArgs e)
        {

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            lbl_TesterMes1.BorderType =GlobalVariable.TestMesEnable1 ? eBorderType.Sunken : eBorderType.Raised;
            lbl_TesterMes1.Text = GlobalVariable.TestMesEnable1 ? "启用" : "禁用";
            lbl_TesterMes1.BackColor = GlobalVariable.TestMesEnable1 ? Color.Transparent : Color.Red;
            lbl_TesterMes1.ForeColor = GlobalVariable.TestMesEnable1 ? Color.LimeGreen : Color.White;

            lbl_TesterMes2.BorderType = GlobalVariable.TestMesEnable2 ? eBorderType.Sunken : eBorderType.Raised;
            lbl_TesterMes2.Text = GlobalVariable.TestMesEnable2 ? "启用" : "禁用";
            lbl_TesterMes2.BackColor = GlobalVariable.TestMesEnable2 ? Color.Transparent : Color.Red;
            lbl_TesterMes2.ForeColor = GlobalVariable.TestMesEnable2 ? Color.LimeGreen : Color.White;

            lbl_handlerMes.BorderType = SystemConfig.Instance.MesParam.EnableMES ? eBorderType.Sunken : eBorderType.Raised;
            lbl_handlerMes.Text = SystemConfig.Instance.MesParam.EnableMES ? "启用" : "禁用";
            lbl_handlerMes.BackColor = SystemConfig.Instance.MesParam.EnableMES ? Color.Transparent : Color.Red;
            lbl_handlerMes.ForeColor = SystemConfig.Instance.MesParam.EnableMES ? Color.LimeGreen : Color.White;
        }

        private void labelItem37_Click(object sender, EventArgs e)
        {
            if (SystemConfig.Instance.MesParam.EnableMES)
            {
                MachineMessageScheduler.Instance.Add(new MachineMessage(MessageType.Log, "人工设置Mes不启用", "系统", 0, "系统"));
                SystemConfig.Instance.MesParam.EnableMES = false;
                lbl_handlerMes.BorderType = SystemConfig.Instance.MesParam.EnableMES ? eBorderType.Sunken : eBorderType.Raised;
                lbl_handlerMes.Text = SystemConfig.Instance.MesParam.EnableMES ? "启用" : "禁用";
                lbl_handlerMes.BackColor = SystemConfig.Instance.MesParam.EnableMES ? Color.Transparent : Color.Red;
                lbl_handlerMes.ForeColor = SystemConfig.Instance.MesParam.EnableMES ? Color.LimeGreen : Color.White;
                MesSendSts(false);
            }
            else
            {
                MachineMessageScheduler.Instance.Add(new MachineMessage(MessageType.Log, "人工设置Mes启用", "系统", 0, "系统"));
                SystemConfig.Instance.MesParam.EnableMES = true;
                lbl_handlerMes.BorderType = SystemConfig.Instance.MesParam.EnableMES ? eBorderType.Sunken : eBorderType.Raised;
                lbl_handlerMes.Text = SystemConfig.Instance.MesParam.EnableMES ? "启用" : "禁用";
                lbl_handlerMes.BackColor = SystemConfig.Instance.MesParam.EnableMES ? Color.Transparent : Color.Red;
                lbl_handlerMes.ForeColor = SystemConfig.Instance.MesParam.EnableMES ? Color.LimeGreen : Color.White;
                MesSendSts(true);
            }
        }
        public void MesSendSts(bool enable)
        {
            if (!SystemConfig.Instance.UsingStatus.IsFrontDisable)
            {
                if (MachineResource.Instance.MachineTcpClient.ContainsKey("一键熄屏1"))
                {
                    TCPClient client = MachineResource.Instance.MachineTcpClient["一键熄屏1"];
                    if (!client.IsConnected)
                        client.Connect();
                    string str = $"Mes,{(enable ? "enable" : "disenable")}\r\n";
                    client.Send(str);
                    MachineMessageScheduler.Instance.Add(new MachineMessage(MessageType.Log, $"PC-->Tester1:{str}", "系统", 0, "系统"));
                }
            }
            if (!SystemConfig.Instance.UsingStatus.IsBackDisable)
            {
                if (MachineResource.Instance.MachineTcpClient.ContainsKey("一键熄屏2"))
                {
                    TCPClient client = MachineResource.Instance.MachineTcpClient["一键熄屏2"];
                    if (!client.IsConnected)
                        client.Connect();
                    string str = $"Mes,{(enable ? "enable" : "disenable")}\r\n";
                    client.Send(str);
                    MachineMessageScheduler.Instance.Add(new MachineMessage(MessageType.Log, $"PC-->Tester2:{str}", "系统", 0, "系统"));
                }
            }
        }
        private void Client_DatagramReceived1(object sender, TcpClientDatagramReceivedEventArgs<byte[]> e)
        {
            string str = Encoding.ASCII.GetString(e.Datagram);
            MachineMessageScheduler.Instance.Add(new MachineMessage(MessageType.Log, $"PC<--Tester1:{str}", "系统", 0, "系统"));
            if (str.Contains("Mes,enable"))
            {
                GlobalVariable.TestMesEnable1 = true;
            }
            else if (str.Contains("Mes,disenable"))
            {
                GlobalVariable.TestMesEnable1 = false;
            }
        }
        private void Client_DatagramReceived2(object sender, TcpClientDatagramReceivedEventArgs<byte[]> e)
        {
            string str = Encoding.ASCII.GetString(e.Datagram);
            MachineMessageScheduler.Instance.Add(new MachineMessage(MessageType.Log, $"PC<--Tester2:{str}", "系统", 0, "系统"));
            if (str.Contains("Mes,enable"))
            {
                GlobalVariable.TestMesEnable2 = true;
            }
            else if (str.Contains("Mes,disenable"))
            {
                GlobalVariable.TestMesEnable2 = false;
            }
        }
    }
    public class AlarmDistribution
    {
        public string AlarmName { get; set; }
        public int AlarmNum { get; set; }
    }
    public class MyGridRadialMenuEditControl : GridRadialMenuEditControl
    {
        public MyGridRadialMenuEditControl()
        {
            SetRadialMenu();
        }

        #region SetRadialMenu

        private void SetRadialMenu()
        {
            Image = Properties.Resources.火箭32;
            //SymbolSize = 13;
            Diameter = 300;

            RadialMenuItem item = new RadialMenuItem();
            item.Text = "普通速度";
            item.Image = Properties.Resources.兔子32;
            item.Click += Item_Click;
            Items.Add(item);

            item = new RadialMenuItem();
            item.Text = "调试速度";
            item.Image = Properties.Resources.乌龟32;
            Items.Add(item);

            item = new RadialMenuItem();
            item.Text = "工作速度";
            item.Image = Properties.Resources.火箭32;
            Items.Add(item);
        }
        #region InitializeContext
        public override void InitializeContext(GridCell cell, CellVisualStyle style)
        {
            base.InitializeContext(cell, style);

            if (style != null)
            {
                Color baseColor;

                RadialMenuItem item = FindItemByText(Items, EditorValue as string);

                if (item != null)
                {
                    Image = item.Image;
                    baseColor = Color.Green;
                }
                else
                {
                    //Symbol = "\uf040";
                    baseColor = Color.Empty;
                }

                if (cell.SuperGrid.NonModalEditorCell == cell)
                    baseColor = Color.Firebrick;

                Colors.RadialMenuButtonBorder = baseColor;
            }
        }

        #endregion

        private void Item_Click(object sender, EventArgs e)
        {
            this.Image = Properties.Resources.兔子32;
        }

        #endregion
    }
}
